package com.lynn.accesstoken.service.impl;

import com.lynn.accesstoken.bean.AppEntity;
import com.lynn.accesstoken.repo.AppEntityRepo;
import com.lynn.accesstoken.service.IAppEntityService;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * @ClassName AccessTokenServiceImpl
 * @Description TODO
 * @Author ly
 * @Date 2019-05-30 16:46
 * @Version 1.0
 */
@Service
public class AppEntityServiceImpl implements IAppEntityService {

    private AppEntityRepo appEntityRepo;

    private MongoTemplate template;

    public AppEntityServiceImpl(AppEntityRepo appEntityRepo, MongoTemplate template) {
        this.template = template;
        this.appEntityRepo = appEntityRepo;
    }

    @Override
    public AppEntity getApp(AppEntity appEntity) {
        return appEntityRepo.findByAppIdAndAppSecret(appEntity.getAppId(), appEntity.getAppSecret());
    }

    @Override
    public AppEntity createApp() {
        AppEntity appEntity = AppEntity.builder()
                .id(System.currentTimeMillis() + "")
                .appId(UUID.randomUUID().toString().replaceAll("-", ""))
                .appSecret(UUID.randomUUID().toString().replaceAll("-", ""))
                .name("测试")
                .flag(1)
                .build();
        AppEntity save = appEntityRepo.save(appEntity);
        return save;
    }

    @Override
    public void updateToken(AppEntity appEntity, String accessToken) {
        template.updateFirst(Query.query(Criteria.where("appId").is(appEntity.getAppId())), Update.update("accessToken", accessToken), AppEntity.class);
    }
}
